package com.xuecheng.content.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.CourseBaseDto;
import com.xuecheng.commons.model.dto.CourseDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.dto.TeachplanDto;
import com.xuecheng.commons.model.vo.CourseBaseVo;
import com.xuecheng.commons.model.vo.PageResponseResult;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.po.CourseBase;
import com.xuecheng.content.domain.po.Teachplan;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2024-05-01
 */
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

    @Override
    public ResponseResult<CourseBaseVo> findByPage(PageRequest pageRequest, CourseDto dto) {
        //1.构建分页
        Page<CourseBase> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());
        //2.构建条件
        page = this.lambdaQuery()
                .like(StrUtil.isNotEmpty(dto.getCourseName()), CourseBase::getName, dto.getCourseName())//课程名称
                .eq(StrUtil.isNotEmpty(dto.getTeachmode()), CourseBase::getTeachmode, dto.getTeachmode())//课程类型
                .page(page);
        //4.转vo
        List<CourseBaseVo> voList = BeanHelper.copyWithCollection(page.getRecords(), CourseBaseVo.class);
        //5.返回结果
        return PageResponseResult.okResult(page.getTotal(), voList);
    }

    /*
     * 课程新增
     * */
    @Override
    public ResponseResult<Map> saveCourseBase(CourseBaseDto dto) {
        //1.校验前端参数 (新增:id和价格不能校验)
        if (!StrUtil.isAllNotEmpty(dto.getName(), dto.getTags(), dto.getMt(), dto.getSt(), dto.getGrade())) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //2.dto转entity
        CourseBase courseBase = BeanHelper.copyProperties(dto, CourseBase.class);
        //3.补全课程信息
        courseBase.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS);
        courseBase.setPlanNum(0);//课程小节数量
        courseBase.setCreateDate(LocalDateTime.now());
        //4.保存数据库
        boolean isSucess = this.save(courseBase);
        if (isSucess == false) {
            throw new BusinessException(ErrorCode.ADDEERROR);
        }
        //5.初始化一级大纲(预留)
        TeachplanVo teachplanVo = new TeachplanVo();
        teachplanVo.setPname(courseBase.getName());
        teachplanVo.setParentid(0L);
        teachplanVo.setGrade(1);//一级
        teachplanVo.setDescription(courseBase.getDescription());
        teachplanVo.setCourseId(courseBase.getId());


        //6.返回课程id
        Map map = new HashMap<>();
        map.put("courseBaseId", courseBase.getId());
        return ResponseResult.okResult(map);
    }

    /*
     * 课程修改
     * */
    @Override
    public ResponseResult<Map> updateCourseBase(CourseBaseDto dto) {
        //1.校验前端参数(修改:价格不能校验)
        if (!StrUtil.isAllNotEmpty(dto.getName(), dto.getTags(), dto.getMt(), dto.getSt(), dto.getGrade())) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        if (ObjectUtil.isEmpty(dto.getId())) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //2.校验课程状态
        //2-1 查询数据库
        CourseBase oldCourseBase = this.getById(dto.getId());
        //2-2 判断状态
        if (StrUtil.equals(oldCourseBase.getAuditStatus(), CourseConstants.AUDIT_PUBLISHED_STATUS)) {
            //已发布(上架)课程,不能改
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //3.dto转实体
        CourseBase newcourseBase = BeanHelper.copyProperties(dto, CourseBase.class);
        newcourseBase.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS);//设置课程状态未提交
        //4.更新数据库
        boolean isSucess = this.updateById(newcourseBase);
        if (isSucess == false) {
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }
        //5.更新课程计划(一级大纲)


        //6.返回课程id
        Map map = new HashMap<>();
        map.put("courseBaseId", oldCourseBase.getId());
        return ResponseResult.okResult(map);
    }

    @Autowired
    private TeachplanService teachplanService;

    /*
     * 课程删除
     * */
    @Override
    @Transactional
    public ResponseResult deleteCourseBase(Long courseId) {
        //1.校验课程状态
        //1-1根据id查询课程
        CourseBase courseBase = this.getById(courseId);
        //1-2 判断是否已发布
        if (StrUtil.equals(CourseConstants.AUDIT_PUBLISHED_STATUS, courseBase.getAuditStatus())) {
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        //2.删除课程
        boolean isSucess = this.removeById(courseId);
        if (isSucess == false) {
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        // 该课程下有1 2 3级不允许删除
        Long count = teachplanService.lambdaQuery()
                .eq(Teachplan::getCourseId, courseId).count();
        if (count > 1) {
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        //只有1级是可以删除的
        teachplanService.remove(teachplanService.lambdaQuery()
        .eq(Teachplan::getCourseId,count));
        //3.返回删除成功 状态码:200
        return ResponseResult.okResult();
    }
}
